package com.cleaningcloud.erp.service.impl;

import com.cleaningcloud.common.core.utils.DateUtils;
import com.cleaningcloud.common.security.utils.CommunityTypeConversionUtils;
import com.cleaningcloud.common.security.utils.SecurityUtils;
import com.cleaningcloud.erp.api.domain.ErpCommodityStockAlter;
import com.cleaningcloud.erp.api.domain.ErpWareCommodityNumber;
import com.cleaningcloud.erp.api.domain.ErpWareHouse;
import com.cleaningcloud.erp.api.utils.StockCommodityAlterUtils;
import com.cleaningcloud.erp.domain.ErpCommodityUnit;
import com.cleaningcloud.erp.domain.ErpProcure;
import com.cleaningcloud.erp.domain.ErpWarehousing;
import com.cleaningcloud.erp.domain.dto.ErpProcureDto;
import com.cleaningcloud.erp.domain.dto.ErpWarehousingDetailsDto;
import com.cleaningcloud.erp.domain.dto.ErpWarehousingDto;
import com.cleaningcloud.erp.domain.vo.ErpProcureVo;
import com.cleaningcloud.erp.domain.vo.ErpWarehousingDetailsVo;
import com.cleaningcloud.erp.domain.vo.ErpWarehousingVo;
import com.cleaningcloud.erp.mapper.*;
import com.cleaningcloud.erp.service.IErpWarehousingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 采购入库Service业务层处理
 *
 * @author cleaningcloud
 * @date 2024-09-29
 */
@Service
public class ErpWarehousingServiceImpl implements IErpWarehousingService {

    @Autowired
    private ErpWarehousingMapper erpWarehousingMapper;
    @Autowired
    private ErpWareCommodityNumberMapper erpWareCommodityNumberMapper;
    @Autowired
    private ErpCommodityUnitMapper erpCommodityUnitMapper;
    @Autowired
    private ErpCommodityStockAlterMapper erpCommodityStockAlterMapper;
    @Autowired
    private ErpProcureMapper erpProcureMapper;
    @Autowired
    private ErpWareHouseMapper erpWareHouseMapper;

    /**
     * 查询采购入库
     *
     * @param warehousingId 采购入库主键
     * @return 采购入库
     */
    @Override
    public ErpWarehousingVo selectErpWarehousingByWarehousingId(Long warehousingId) {
        ErpWarehousingVo erpWarehousingVo = erpWarehousingMapper.selectErpWarehousingByWarehousingId(warehousingId);
        for (ErpWarehousingDetailsVo erpWarehousingDetailsVo : erpWarehousingVo.getDetailsList()) {
            erpWarehousingDetailsVo.setCommodityType(CommunityTypeConversionUtils.conversion(erpWarehousingDetailsVo.getCommodityType()));
            erpWarehousingDetailsVo.setThisIssue(erpWarehousingDetailsVo.getPendingNumber() - erpWarehousingDetailsVo.getRealityNumber());
            // 查询商品单位列表
            ErpCommodityUnit query = new ErpCommodityUnit();
            query.setCommodityId(erpWarehousingDetailsVo.getCommodityId());
            erpWarehousingDetailsVo.setUnitList(erpCommodityUnitMapper.selectErpCommodityUnitList(query));
        }
        return erpWarehousingVo;
    }

    /**
     * 查询采购入库列表
     *
     * @param erpWarehousing 采购入库
     * @return 采购入库
     */
    @Override
    public List<ErpWarehousingVo> selectErpWarehousingList(ErpWarehousingDto erpWarehousing) {
        return erpWarehousingMapper.selectErpWarehousingList(erpWarehousing);
    }

    /**
     * 新增采购入库
     *
     * @param erpWarehousing 采购入库
     * @return 结果
     */
    @Override
    public int insertErpWarehousing(ErpWarehousing erpWarehousing) {
        if(null == erpWarehousing.getWareId()){
            throw new RuntimeException("入库仓库不能为空，请重新选择！");
        }else{
            ErpWareHouse obj = erpWareHouseMapper.selectErpWareHouseByWareId(erpWarehousing.getWareId());
            if(null != obj){
                erpWarehousing.setCreateTime(DateUtils.getNowDate());
                erpWarehousing.setWarehousingTime(DateUtils.getNowDate());
                erpWarehousing.setFlag("Y");
                erpWarehousing.setCreateId(SecurityUtils.getUserId());
                erpWarehousing.setCreateName(SecurityUtils.getUsername());
                return erpWarehousingMapper.insertErpWarehousing(erpWarehousing);
            }else{
                throw new RuntimeException("入库仓库不能为空，请重新选择！");
            }
        }
    }

    /**
     * 修改采购入库
     *
     * @param erpWarehousing 采购入库
     * @return 结果
     */
    @Override
    @Transactional
    public int updateErpWarehousing(ErpWarehousingDto erpWarehousing) {
        if(null == erpWarehousing.getWareId()){
            throw new RuntimeException("入库仓库不能为空，请重新选择！");
        }
        erpWarehousing.setWarehousingTime(new Date());
        erpWarehousing.setCreateId(SecurityUtils.getUserId());
        erpWarehousing.setCreateName(SecurityUtils.getUsername());
        // 统计总已入库量
        int totalReality = 0;
        // 统计采购总量
        int sumReality = 0;
        for (ErpWarehousingDetailsDto warehousingDetails : erpWarehousing.getDetailsList()) {
            // 判断
            if (warehousingDetails.getThisIssue() > warehousingDetails.getPendingNumber()) {
                throw new RuntimeException("本期入库数量不可大于待入库数量！");
            }
            if (warehousingDetails.getUnitResult() <= 0) {
                warehousingDetails.setUnitResult(1);
            }
            // 计算已入库
            warehousingDetails.setRealityNumber(warehousingDetails.getRealityNumber() + warehousingDetails.getThisIssue());
            totalReality += warehousingDetails.getRealityNumber();
            sumReality += warehousingDetails.getProcureNumber();
            // 计算待入库
            warehousingDetails.setPendingNumber(warehousingDetails.getProcureNumber() - warehousingDetails.getRealityNumber());
            erpWarehousingMapper.updateErpWarehousingDetails(warehousingDetails);
            // 根据商品id和仓库id查询库存商品数量表 修改库存数量 （本期入库+库存数量=库存数量）
            ErpWareCommodityNumber query = new ErpWareCommodityNumber();
            query.setCommodityId(warehousingDetails.getCommodityId());
            query.setWareId(erpWarehousing.getWareId());
            ErpWareCommodityNumber erpWareCommodityNumber = erpWareCommodityNumberMapper.selectByCommodityIdAndWareId(query);
            if (erpWareCommodityNumber == null) {
                // 为空则新增
                erpWareCommodityNumber = new ErpWareCommodityNumber();
                erpWareCommodityNumber.setCommodityId(warehousingDetails.getCommodityId());
                erpWareCommodityNumber.setWareId(erpWarehousing.getWareId());
                erpWareCommodityNumber.setCommodityNumber(warehousingDetails.getThisIssue() * warehousingDetails.getUnitResult());
                erpWareCommodityNumber.setStartNumber(warehousingDetails.getThisIssue());
                erpWareCommodityNumberMapper.insertErpWareCommodityNumber(erpWareCommodityNumber);
            } else {
                erpWareCommodityNumber.setCommodityNumber((warehousingDetails.getThisIssue() * warehousingDetails.getUnitResult()) + erpWareCommodityNumber.getCommodityNumber());
                erpWareCommodityNumber.setWareId(erpWarehousing.getWareId());
                erpWareCommodityNumberMapper.updateErpWareCommodityNumber(erpWareCommodityNumber);
            }
            // 新增库存商品变更记录信息
            ErpCommodityStockAlter erpCommodityStockAlter = StockCommodityAlterUtils.AssemblyInfo(warehousingDetails.getCommodityId(), BigDecimal.valueOf(warehousingDetails.getThisIssue()), "1", erpWarehousing.getWareId());
            erpCommodityStockAlterMapper.insertErpCommodityStockAlter(erpCommodityStockAlter);
        }
        // 已入库量等于采购总量 修改状态为已入库
        if (sumReality == totalReality) {
            erpWarehousing.setWarehousingStatus(2);
        }

        //修改采购单的物流状态
        ErpProcureDto dto = new ErpProcureDto();
        dto.setProcureNo(erpWarehousing.getProcureOdd());
        List<ErpProcureVo> list = erpProcureMapper.selectErpProcureList(dto);
        if(!list.isEmpty()){
            list.get(0).setLogisticsStauts("2");
            erpProcureMapper.updateErpProcure(list.get(0));
        }
        erpWarehousingMapper.updateErpWarehousing(erpWarehousing);
        return 1;
    }

    /**
     * 批量删除采购入库
     *
     * @param warehousingIds 需要删除的采购入库主键
     * @return 结果
     */
    @Override
    public int deleteErpWarehousingByWarehousingIds(Long[] warehousingIds) {
        return erpWarehousingMapper.deleteErpWarehousingByWarehousingIds(warehousingIds);
    }

    /**
     * 删除采购入库信息
     *
     * @param warehousingId 采购入库主键
     * @return 结果
     */
    @Override
    public int deleteErpWarehousingByWarehousingId(Long warehousingId) {
        return erpWarehousingMapper.deleteErpWarehousingByWarehousingId(warehousingId);
    }
}
